export interface IWidgetDesc {
  /** 组件标识 */
  key: string;
  /** 提示文案 */
  label: string;
  /** 菜单中显示 */
  preview(): JSX.Element;
  render(): JSX.Element;
}

function isArrayWidgetDesc(x: IWidgetDesc | IWidgetDesc[]): x is IWidgetDesc[] {
  return Array.isArray(x);
}

/**
 * 用于注册组件
 */
export function createWidgetConfig() {
  const componentList: IWidgetDesc[] = [];
  const componentMap: Map<string, IWidgetDesc> = new Map();

  function registry(widgetDesc: IWidgetDesc | IWidgetDesc[]) {
    const temp: IWidgetDesc[] = isArrayWidgetDesc(widgetDesc)
      ? widgetDesc
      : [widgetDesc];

    temp.forEach(item => {
      if (componentMap.has(item.key)) {
        console.warn(`${item.key} have already registered`);
        return;
      }
      componentList.push(item);
      componentMap.set(item.key, item);
    });
  }

  return {
    componentList,
    componentMap,
    registry,
  };
}
